package com.jeequan.jeepay.pay.channel.airpay.payway;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.PayOrder;
import com.jeequan.jeepay.core.model.params.airpay.AirpayNormalMchParams;
import com.jeequan.jeepay.core.utils.AmountUtil;
import com.jeequan.jeepay.core.utils.DisResultHttp;
import com.jeequan.jeepay.core.utils.DistResult;
import com.jeequan.jeepay.pay.channel.airpay.AirpayPaymentService;
import com.jeequan.jeepay.pay.exception.ChannelException;
import com.jeequan.jeepay.pay.model.MchAppConfigContext;
import com.jeequan.jeepay.pay.rqrs.AbstractRS;
import com.jeequan.jeepay.pay.rqrs.msg.ChannelRetMsg;
import com.jeequan.jeepay.pay.rqrs.payorder.UnifiedOrderRQ;
import com.jeequan.jeepay.pay.rqrs.payorder.payway.AirPcOrderRQ;
import com.jeequan.jeepay.pay.rqrs.payorder.payway.AirPcOrderRS;
import com.jeequan.jeepay.pay.util.ApiResBuilder;
import com.paypal.orders.OrderRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
//import org.springframework.web.reactive.function.client.WebClient;
// 其他导入...

import java.math.BigDecimal;
import java.util.Map;

/**
 * none.
 *
 * @author 陈泉
 * @package com.jeequan.jeepay.pay.channel.pppay.payway
 * @create 2021/11/15 18:59
 */
@Slf4j
@Service("AirpayPaymentByAirPCService")
public class AirPc extends AirpayPaymentService {

    private final static String API_URL = "https://api.airwallex.com";






    @Override
    public String preCheck(UnifiedOrderRQ bizRQ, PayOrder payOrder) {
        return null;
    }

    @Override
    public AbstractRS pay(UnifiedOrderRQ rq, PayOrder payOrder, MchAppConfigContext mchAppConfigContext) throws
            Exception {
        AirPcOrderRQ bizRQ = (AirPcOrderRQ) rq;
        log.debug(JSON.toJSONString(rq));
        OrderRequest orderRequest = new OrderRequest();
        if(StringUtils.isNotBlank(bizRQ.getSuccessUrl())) {
            log.debug("successUrl....");
        }
        AirpayNormalMchParams airpayNormalMchParams = mchAppConfigContext.getNormalMchParamsByIfCode(CS.IF_CODE.AIRPAY, AirpayNormalMchParams.class);
        // 构造函数响应数据
        AirPcOrderRS res = ApiResBuilder.buildSuccess(AirPcOrderRS.class);
        ChannelRetMsg channelRetMsg = new ChannelRetMsg();

        String url = API_URL + "/api/v1/pa/payment_intents/create";
        String token = getToken(airpayNormalMchParams.getClientId(),airpayNormalMchParams.getSecret());
        JSONObject data = new JSONObject();
        data.put("request_id",bizRQ.getMchOrderNo());
        data.put("merchant_order_id",bizRQ.getMchOrderNo());
        BigDecimal amount = new BigDecimal(AmountUtil.convertCent2Dollar(bizRQ.getAmount()));
        data.put("amount",amount);
        data.put("currency",bizRQ.getCurrency());
        if(StringUtils.isNotEmpty(bizRQ.getChannelUserId())){
            data.put("customer_id",bizRQ.getChannelUserId());
        }
        JSONObject order = new JSONObject();
        JSONArray products = new JSONArray();
        JSONObject product = new JSONObject();
//        product.put("code",productCode);
        product.put("name",bizRQ.getSubject());
        product.put("desc",bizRQ.getBody());
        product.put("quantity",1);
//        product.put("sku",productCode);
        product.put("type","intangible");
        product.put("unit_price",amount);
        products.add(product);
        order.put("products",products);
        order.put("type","intangible_good");
        data.put("order",order);
//        HttpEntity request = new HttpEntity<>(JSON.toJSONString(data));
        DistResult result = DisResultHttp.doPostHttpsAir(url, data,token, "");
//        JSONObject response = restTemplate.postForObject(url, request, JSONObject.class);
        log.debug(JSON.toJSONString(result));
        Map response = (Map<String, Object>) result.getData();
        String intentId = response.get("id").toString();
        String clientSecret = response.get("client_secret").toString();
        // 构造函数响应数据
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("https://checkout.airwallex.com/#/standalone/checkout?");
            sb.append("intent_id=").append(intentId).append("&");
            sb.append("client_secret=").append(clientSecret).append("&");
            sb.append("mode=payment&currency=").append(bizRQ.getCurrency());
            res.setPayUrl(sb.toString());
        }catch (Exception e) {
            throw ChannelException.sysError(e.getMessage());
        }

        res.setChannelRetMsg(channelRetMsg);

        //放置 响应数据
        channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.WAITING);
        return res;
    }

    private String getToken(String clientId, String secret) {
        String url = API_URL + "/api/v1/authentication/login";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("x-client-id", clientId);
        headers.set("x-api-key", secret);
        HttpEntity<String> request = new HttpEntity<>(null, headers);
        DistResult result = null;
        try {
            result = DisResultHttp.doPostHttpsAirByToken(url, request,clientId, secret);
        }catch (Exception e) {
            e.printStackTrace();
        }
        Map response = (Map<String, Object>) result.getData();

//        String response = restTemplate.postForObject(url, request, String.class);
        System.out.println(response);
        String token = response.get("token").toString();
        return token;
    }
}
